package com.oraycn.esbasic.helpers;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class TimeHelper {


	public static Date addDay(Date sourceDate,int dayCount)
	{
		return addCalendar(sourceDate, Calendar.DATE,dayCount);
	}

	public static Date addMonth(Date sourceDate,int months)
	{
		return addCalendar(sourceDate, Calendar.MONTH,months);
	}

	public static Date addYear(Date sourceDate,int years)
	{
		return addCalendar(sourceDate, Calendar.YEAR,years);
	}

	public static Date addHour(Date sourceDate,int hours)
	{
		return addCalendar(sourceDate, Calendar.HOUR,hours);
	}

	public static Date addMinute(Date sourceDate,int mins)
	{
		return addCalendar(sourceDate, Calendar.MINUTE,mins);
	}

	public static Date addSecond(Date sourceDate,int secs)
	{
		return addCalendar(sourceDate, Calendar.SECOND,secs);
	}

	private static  Date addCalendar(Date sourceDate,int calendarType, int changeValue)
	{
		Calendar calendar  =  new GregorianCalendar();
		calendar.setTime(sourceDate);
		calendar.add(calendarType,changeValue);
		return calendar.getTime();
	}

	/**
	 * 获取服务器时间
	 * 
	 * @return 服务器时间 或null
	 */
	public static Timestamp getSystemTime() throws Exception {
		URL url = new URL("http://www.oraycn.com/authorizeservice.asmx");
		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
		BufferedInputStream bis = new BufferedInputStream(TimeHelper.class
				.getClassLoader().getResourceAsStream(
                        "com/oraycn/es/communicate/utils/SOAP.xml"));
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		copy(bis, bout);
		bis.close();
		byte[] b = bout.toByteArray();
		httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
		httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		httpConn.setRequestProperty("SOAPAction",
				"http://www.oraycn.com/GetTime");
		httpConn.setRequestMethod("POST");
		httpConn.setDoOutput(true);
		httpConn.setDoInput(true);
		OutputStream out = httpConn.getOutputStream();
		out.write(b);
		out.close();
		InputStream isr = httpConn.getInputStream();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();// 创建一个document解析的工厂
		DocumentBuilder builder = factory.newDocumentBuilder();// dom解析器，
		Document document = builder.parse(isr);// 解析xml文件流获得文档对象
		Element element = document.getDocumentElement();// 获得文档元素节点

		NodeList personNodeList = element
				.getElementsByTagName("GetTimeResponse");
		int len = personNodeList.getLength();
		if (len > 0) {
			personNodeList.item(0).getNodeName();
			String time = personNodeList.item(0).getChildNodes().item(0)
					.getFirstChild().getNodeValue();
			return new Timestamp(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
					.parse(time).getTime());
		}
		return null;
	}

	/**
	* 是否超时
	* @param endTime 结束时间
	 * @return true：已超时；false：未超时
	* */
	public static boolean isTimeover(Timestamp endTime) {
		Timestamp nowTime = null;
		try {
			nowTime = getSystemTime();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		if (nowTime.getTime() > endTime.getTime()) {
			return true;
		} else {
			return false;
		}

	}

	private static void copy(InputStream in, OutputStream out)
			throws IOException {
		synchronized (in) {
			synchronized (out) {
				byte[] buffer = new byte[256];
				while (true) {
					int bytesRead = in.read(buffer);
					if (bytesRead == -1)
						break;
					out.write(buffer, 0, bytesRead);
				}
			}
		}
	}

	/**
	 * 获取最近时间字符串
	 * @param time
	 * @return  11月1日  或者 当天的  10：21
	 */
	public static String getTimeStr4Now(Date time)
	{
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(new Date());
		Calendar today =  GregorianCalendar.getInstance();//calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1,calendar.get(Calendar.DATE));
		today.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DATE),0,0,0);
		Date yesterday = addDay(today.getTime(),-1);
		SimpleDateFormat dateFormat=null;//new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		if(time.after(today.getTime()))
		{
			dateFormat=new SimpleDateFormat("HH:mm");
		}else if(time.after(yesterday)){
			return "昨天";
		}else {
			dateFormat=new SimpleDateFormat("MM月dd日");
		}
		return dateFormat.format(time);
	}
}
